package org.example.config.controller;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.config.domain.Result;
import org.example.config.domain.ResultCodeEnum;
import org.example.config.util.AliyunSmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("user")
@Slf4j
@CrossOrigin
public class AliyunController {
    @Autowired
    private AliyunSmsUtil aliyunSmsUtil;

    private static final String PHONE_NUMBER_REGEX = "^1[34578]\\d{9}$";

    public static boolean validatePhoneNumber(String phoneNumber) {
        // 创建手机号码正则表达式的模式
        Pattern pattern = Pattern.compile(PHONE_NUMBER_REGEX);
        // 使用模式匹配手机号码
        Matcher matcher = pattern.matcher(phoneNumber);
        // 返回匹配结果
        return matcher.matches();
    }
    @RequestMapping("sendSms/{phoneNumber}")
    public Result sendSms(@PathVariable String phoneNumber){
        if (!validatePhoneNumber(phoneNumber)){
            return Result.build(ResultCodeEnum.PHONE_ERROR.getCode(),ResultCodeEnum.PHONE_ERROR.getMessage());
        }

        String code = RandomUtil.randomInt(1, 10)+"-"+RandomUtil.randomInt(10, 100)+"-"+RandomUtil.randomInt(10, 100);
        log.info("生成的取件码：{}",code);

        aliyunSmsUtil.sendSms(phoneNumber,code);
        log.info("发送取件码：{}",code);

        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());
    }
}
